package cn.q3c.download.api;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Calendar;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import cn.keyvalue.ccf.common.util.ObjectUtils;
import cn.q3c.download.commons.Configuration;
import cn.q3c.download.commons.DownloadLog;
import cn.q3c.download.commons.DownloadUtils;

public class DownloadAPI {

	private static Logger logger = Logger.getLogger(DownloadAPI.class);
	// 默认返回的最大记录数
	public final static int MAX_RECODECOUNT = 5000;

	/**
	 * 搜索第一个满足条件的文件，3天内
	 * @param projectName
	 * @param keywords
	 * @return
	 * @throws ParseException 
	 * @throws IOException 
	 */
	public static File searchFileByUrl( String projectName, String keywords ) throws IOException, ParseException
	{
		File retFile = null;
		
		List<DownloadLog> downloadLogList = getDownloadLogList(projectName,
				DateUtils.addDays(new Date(), -3), new Date());
		
		if( !ObjectUtils.isEmptyList(downloadLogList) )
		{
			for( DownloadLog downloadLog:downloadLogList )
			{
				if( StringUtils.contains(downloadLog.getUrl(),keywords ) )
				{
					retFile = downloadLog.getFile();
					break;
				}						
			}
		}
		
		return retFile;
	}
	
	
	/**
	 * 获取指定分钟内的最新日志 最大1000条
	 * eg.2*(int)(DateUtils.MILLIS_PER_DAY/DateUtils.MILLIS_PER_MINUTE) 2天
	 * 
	 * @param projectName
	 * @param limit
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static List<DownloadLog> getDownloadLogList(String projectName,
			int minute) throws IOException, ParseException {

		Date endDate = new Date();
		Date startDate = DateUtils.addMinutes(endDate, 0 - minute);

		return getDownloadLogList(projectName, startDate, endDate);
	}

	/**
	 * 时间段
	 * 
	 * @param projectName
	 * @param fromDate
	 * @param minute
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public static List<DownloadLog> getDownloadLogList(String projectName,
			Date fromDate, Date toDate) throws IOException, ParseException {

		if (toDate.getTime() <= fromDate.getTime()) {
			logger.error("起始时间不能大于终止时间：" + fromDate + " " + toDate);
			return null;
		}
		
		File savePath = new File(Configuration.getInstance().getStorePath());
		if( !savePath.exists() )
		{
			logger.error("download系统数据文件路径不存在，" + savePath + ",请检查java环境变量 download.data.path");
			return null;
		}
		
		//项目配置日志路径是否存在，不存在退出
		File logPath = new File(DownloadUtils.getProjectLogsPath( projectName ));
		if( !logPath.exists() )
		{
			logger.error( projectName + "项目的日志路径不存在 " + logPath);
			return null;
		}

		Date endDate = toDate;
		Date startDate = fromDate;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endDate);

		List<DownloadLog> retList = new ArrayList<DownloadLog>();
		while (true) {
			if (calendar.getTimeInMillis() < startDate.getTime()) {
				break;
			}

			String logFile = DownloadUtils.getProjectLogFile(projectName,
					calendar.getTime());
			List<DownloadLog> logList = DownloadUtils
					.fileToDownloadLogList(new File(logFile));

			if (!ObjectUtils.isEmptyList(logList)) {
				for (int i = logList.size() - 1; i >= 0; i--) {
					DownloadLog log = logList.get(i);
					if (log.getDate().getTime() >= startDate.getTime()
							&& log.getDate().getTime() <= endDate.getTime()
							&& log.getFile().exists())// 下载成功的，文件不存在不返回
					{
						retList.add(log);
						if (retList.size() >= MAX_RECODECOUNT) {
							return retList;
						}
					}
				}
			}

			calendar.add(Calendar.HOUR, -1);
		}

		return ObjectUtils.isEmptyList(retList) ? null : retList;
	}

	public static void main(String[] args) throws IOException, ParseException {
		System.out
				.println(getDownloadLogList(
						"testSpider",
						2 * (int) (DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_MINUTE))
						.size());
	}
}